package activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import net.ck.hzq.R;
import net.ck.hzq.RecognizeService;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.model.TakePhotoOptions;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;

import Utils.AccountUtils;
import Utils.FileUtil;
import Utils.HelloWordModel;
import Utils.OCRUtils;
import Utils.ToastUtil;
import activity.glide.GlideApp;
import base.BaseActivity;
import base.BaseTakePhotoActivity;
import dao.BaseOutput;
import dao.ChangeBalanceCardInput;
import event.LoginEvent;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static Utils.FileUtil.compress;

public class ChangeBalanceCardActivity extends BaseTakePhotoActivity implements View.OnClickListener {


    private ImageView ivCardFront, ivCardBack;
    private AppCompatEditText tvBankNo, tvBankName;
    private AppCompatEditText etMerchantName, etMerchantNo, etOpenAccountBank;
    private String base64_card_front, base64_card_back;
    private String mCardNum, mCardBank;
    private int clickType = -1;
    @Override
    public int getLayoutId() {
        return R.layout.activity_change_balance_card;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        findViewById(R.id.iv_back).setOnClickListener(v -> finish());

        ivCardFront = findViewById(R.id.iv_card_front);
        ivCardBack = findViewById(R.id.iv_card_back);
        tvBankNo = findViewById(R.id.tv_card_no);
        tvBankName = findViewById(R.id.tv_card_bank_name);
        etMerchantName = findViewById(R.id.et_merchant_name);
        etMerchantNo = findViewById(R.id.et_merchant_no);
        etOpenAccountBank = findViewById(R.id.et_open_account_bank);

        ivCardFront.setOnClickListener(this);
        ivCardBack.setOnClickListener(this);
        findViewById(R.id.submit).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_card_front:
//                OCRUtils.startBankCard(this, 11);

                clickType = 1;
                cameraClick(clickType,getTakePhoto());

                break;
            case R.id.iv_card_back:
//                OCRUtils.startBankCardBack(this, 12);
                clickType = 2;
                cameraClick(clickType,getTakePhoto());

                break;
            case R.id.submit:
                submitData();
                break;
        }
    }
    //拍照
    private void cameraClick(int type, TakePhoto takePhoto) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Uri imageUri = Uri.fromFile(file);
        configCompress(takePhoto);
        configTakePhotoOption(takePhoto);
        takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
    }
    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true); //使用TakePhoto自带小相册
        builder.setCorrectImage(true); //纠正拍照的照片旋转角度
        takePhoto.setTakePhotoOptions(builder.create());
    }

    private CropOptions getCropOptions() {
        int height = 600;
        int width = 800;
        boolean withWonCrop = false;

        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    private void configCompress(TakePhoto takePhoto) {
        int maxSize = 102400;
        int width = 800;
        int height = 800;
        boolean showProgressBar = false;
        boolean enableRawFile = true;
        CompressConfig config;
//        if (rgCompressTool.getCheckedRadioButtonId() == R.id.rbCompressWithOwn) {
        config = new CompressConfig.Builder().setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
//        } else {
//            LubanOptions option = new LubanOptions.Builder().setMaxHeight(height).setMaxWidth(width).setMaxSize(maxSize).create();
//            config = CompressConfig.ofLuban(option);
//            config.enableReserveRaw(enableRawFile);
//        }
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        showImg(result.getImages());

    }
    //    private ImageView idFrontIv, idBackIv, holdIv, bankCardIv,hand_image_bank_card_back, businessLicenseIv,hand_image_id_door,hand_image_id_enerment;
//private String base64_id_front, base64_id_back, base64_hand, base64_back_card,base64_back_card_back,
//        base64_business_license, base64_door,base64_environment;
    private void showImg(ArrayList<TImage> images) {
        if (clickType == 1){
            base64_card_front = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(ivCardFront);
        }
        else if (clickType == 2){
            base64_card_back = "data:image/jpg;base64," + compress(images.get(images.size() - 1).getCompressPath());
            Glide.with(this).load(new File(images.get(images.size() - 1).getCompressPath())).into(ivCardBack);
        }

    }



    private void submitData() {
        if (TextUtils.isEmpty(etMerchantName.getText().toString().trim())
                || TextUtils.isEmpty(etMerchantNo.getText().toString().trim())
                || TextUtils.isEmpty(etOpenAccountBank.getText().toString().trim())
                || TextUtils.isEmpty(base64_card_front)
                || TextUtils.isEmpty(base64_card_back)
                || TextUtils.isEmpty(tvBankNo.getText().toString().trim())
                || TextUtils.isEmpty(tvBankName.getText().toString().trim())) {
            showFailureTipDialog("请输入所有必要信息");
            return;
        }

        showProgressDialog();

        ChangeBalanceCardInput input = new ChangeBalanceCardInput();
        input.customId = AccountUtils.getCustomId();
        input.merchantName = etMerchantName.getText().toString().trim();
        input.merchantNo = etMerchantNo.getText().toString().trim();
        input.bankCardNumber = tvBankNo.getText().toString().trim();
        input.bank = tvBankName.getText().toString().trim();
        input.bankFont = base64_card_front;
        input.bankBack = base64_card_back;
        input.khzh = etOpenAccountBank.getText().toString().trim();
        HelloWordModel.getInstance(this).changeBalanceCard(input).enqueue(new Callback<BaseOutput<Object>>() {
            @Override
            public void onResponse(Call<BaseOutput<Object>> call, Response<BaseOutput<Object>> response) {
                dismissProgressDialog();
                try {
                    if (response.body() != null && "401".equals(response.body().result)) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else if (response.body() != null && response.body().msg.equals("success")) {
                        ToastUtil.showNormal(ChangeBalanceCardActivity.this, "提交成功");
                        finish();
                    } else {
                        ToastUtil.showNormal(ChangeBalanceCardActivity.this, response.body().msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<BaseOutput<Object>> call, Throwable t) {
                dismissProgressDialog();
                ToastUtil.showNormal(ChangeBalanceCardActivity.this, "请求失败");
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 11 && resultCode == Activity.RESULT_OK) {
            reBankCard();
        }
        if (requestCode == 12 && resultCode == Activity.RESULT_OK) {
            base64_card_back = "data:image/png;base64," + compress(FileUtil.getBankBackFile(getApplicationContext())
                    .getAbsolutePath());
            GlideApp.with(this)
                    .load(FileUtil.getBankBackFile(getApplicationContext()))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(ivCardBack);
        }
    }

    private void reBankCard() {
//        showProgressDialog();
//        RecognizeService.recBankCard(this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(), result -> {
//            dismissProgressDialog();
//            if (result.contains("error")) {
//                showFailureTipDialog("扫描失败，请重试!");
//            } else {
//                try {
//                    String[] card = result.split("\n");
//                    String s1[] = card[0].split("：");
//                    String s2[] = card[1].split("：");
//                    String s3[] = card[2].split("：");
//
//                    mCardNum = s1[1];
//                    mCardBank = s3[1];
//                    tvBankNo.setText(mCardNum);
//                    tvBankName.setText(mCardBank);
//
//                    base64_card_front = "data:image/png;base64," + compress(FileUtil.getSaveFile(getApplicationContext())
//                            .getAbsolutePath());
//                    GlideApp.with(this)
//                            .load(FileUtil.getSaveFile(getApplicationContext()))
//                            .skipMemoryCache(true) // 不使用内存缓存
//                            .diskCacheStrategy(DiskCacheStrategy.NONE)
//                            .into(ivCardFront);
//                } catch (Exception e) {
//                    showFailureTipDialog("扫描失败，请重试!");
//                }
//            }
//        });
    }
}
